<?php

namespace app\api\controller\mall;

use app\api\library\message\Mini;

use app\api\model\mall\Goods as GoodsModel;

use app\api\model\mall\SkuSpec;
use app\common\controller\Api;
use fast\Http;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['index', 'detail', 'lists', 'getWxCode'];

    //首页推荐商品
    public function index()
    {
        $hots = GoodsModel::where('status', 'normal')
            ->order('weigh desc')
            ->limit(12)
            ->cache(false)
            ->select();
        $recommends = GoodsModel::getIndexGoodsList();
        foreach ($hots as $item) {
            $item->visible(explode(',', 'id,title,price,marketprice,sales,views,image'));
        }
        foreach ($recommends as $item) {
            $item->visible(explode(',', 'id,title,price,marketprice,sales,views,image'));
        }
        $this->success('获取成功', [
            'hots'       => $hots,
            'recommends' => $recommends
        ]);
    }

    //详情
    public function detail()
    {
        $id = $this->request->param('id/d');

        if (!$id) {
            $this->error('参数错误');
        }
        $row = (new GoodsModel())->with([
            'Sku',

        ])->where('status', '<>', 'hidden')->where('id', $id)->find();

        if (!$row) {
            $this->error('未找到该商品');
        }
        $row->setInc('views');

        $row->sku_spec = SkuSpec::getGoodsSkuSpec($id);

        $row->visible(explode(',', 'id,title,subtitle,category_id,price,marketprice,sales,stocks,views,image,content,images,sku_spec,sku,guarantee,attributes,favor_rate,coupon,statement,tips'));
        $row = $row->toArray();

        $this->success('获取成功', $row);
    }

    //列表
    public function lists()
    {
        $param = $this->request->param();
        $pageNum = (int)$this->request->param('pageNum', 10);
        $orderby = $this->request->param('orderby', 'weigh');
        $orderway = $this->request->param('orderway', 'desc');


        $list = GoodsModel::where(function ($query) use ($param) {
            $query->where('status', 'normal');
            if (isset($param['goods_id']) && !empty($param['goods_id'])){

                $query->where('id', '<>',$param['goods_id']);
            }
            if (isset($param['recommend']) && !empty($param['recommend'])){
                $query->where('is_recommend', 1);
            }
            if (isset($param['activity']) && !empty($param['activity'])){
                $query->where('is_activity', 1);
            }
            //关键词
            if (isset($param['keyword']) && !empty($param['keyword'])) {
                $query->where('title|keywords', 'like', '%' . $param['keyword'] . '%');
                /*$log = \addons\shop\model\SearchLog::getByKeywords($param['keyword']);
                if ($log) {
                    $log->setInc("nums");
                } else {
                    \addons\shop\model\SearchLog::create(['keywords' => $param['keyword'], 'nums' => 1, 'status' => 'hidden']);
                }*/
            }
            //分类
            if (isset($param['category_id']) && !empty($param['category_id'])) {
                $query->where('category_id', 'IN', \app\admin\model\mall\Category::getCategoryChildrenIds($param['category_id']));
            }

            //dump(\app\api\model\Category::getCategoryChildrenIds($param['category_id']));die;
            //价格
            if (isset($param['price']) && !empty($param['price'])) {
                $priceArr = explode('-', $param['price']);
                if (count($priceArr) == 2) {
                    if (isset($priceArr[0])) {
                        $priceArr[0] = (float)$priceArr[0];
                    }
                    if (isset($priceArr[1])) {
                        $priceArr[1] = (float)$priceArr[1];
                    }
                    $query->where('price', 'BETWEEN', $priceArr);
                }
            }
        })->order("{$orderby} {$orderway}")->paginate($pageNum);

        foreach ($list as $item) {
            $item->visible(explode(',', 'id,title,image,price,sales,views,description,marketprice,createtime'));
        }

        $this->success('', $list);
    }

    //获取小程序码
    public function getWxCode()
    {
        $goods_id = $this->request->post('goods_id');
        if (empty($goods_id)) {
            $this->error('参数错误');
        }
        $user_id = '';
        if ($this->auth->isLogin()) {
            $user_id = $this->auth->id;
        }
        $resource = '';
        $fileStream = (new Mini())->getWxCodeUnlimited([
            'scene' => "invite_id={$user_id}&goods_id={$goods_id}",
            'page'  => 'pages/goods/detail'
        ]);
        if (is_null(json_decode($fileStream))) {
            try {
                $img = imagecreatefromstring($fileStream);
                ob_start();
                imagepng($img);
                $resource = ob_get_clean();
            } catch (\Exception $e) {
                \think\Log::write($e->getMessage());
                $this->error("获取微信二维码失败！");
            }
        } else {
            $config = get_addon_config('shop');
            if ($config['wxapp']) {
                $localFile = ROOT_PATH . 'public' . $config['wxapp'];
                if (is_file($localFile)) {
                    $resource = file_get_contents($localFile);
                } else {
                    $resource = Http::get(cdnurl($config['wxapp'], true));
                }
            }
        }
        if (!$resource) {
            $this->error("获取二维码失败！");
        }
        $base64_data = base64_encode($resource);
        $base64_file = 'data:image/jpg;base64,' . $base64_data;
        $this->success('获取成功', $base64_file);
    }
}
